﻿using UnityEngine;
using System.Collections;
using IndieStudio.BugsBang.Utility;
using UnityEngine.Events;

///Developed By Indie Studio
///https://assetstore.unity.com/publishers/9268
///www.indiestd.com
///info@indiestd.com

namespace IndieStudio.BugsBang.Game
{
	// Escape or Back event

	[DisallowMultipleComponent]
	public class EscapeEvent : MonoBehaviour
	{
		/// <summary>
		/// On escape/back event
		/// </summary>
		public UnityEvent escapeEvent;

		void Update ()
		{
			if (Input.GetKeyDown (KeyCode.Escape)) {
				OnEscapeClick ();
			}
		}

		/// <summary>
		/// On Escape click event.
		/// </summary>
		public void OnEscapeClick ()
		{
			bool visibleDialogFound = HideVisibleDialogs ();
			if (visibleDialogFound) {
				return;
			}
			escapeEvent.Invoke ();
		}

		/// <summary>
		/// Hide the visible dialogs.
		/// </summary>
		/// <returns><c>true</c>, if visible a dialog was visible, <c>false</c> otherwise.</returns>
		private bool HideVisibleDialogs ()
		{
			bool visibleDialogFound = false;
		
			Dialog[] dialogs = GameObject.FindObjectsOfType<Dialog> ();
			if (dialogs != null) {
				foreach (Dialog d in dialogs) {
					if (d.visible) {
						if (d.name == "RenewBoosterDialog" || d.name =="LeaveConfirmDialog") {
							//Do not forget to resume game manager, on escape event for this dialog
							GameManager.instance.Resume ();
						} else if (d.name == "NoLivesDialog" || d.name == "NoTimeDialog") {
							//Disable escpae for this/these dialog(s)
							return true;
						} 

						d.Hide (true);
						visibleDialogFound = true;
					}
				}
			}
			return visibleDialogFound;
		}
	}
}